using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

// 英雄UI组件示例
public class HeroUIExample : MonoBehaviour
{
    [Header("UI组件")]
    public Transform heroListContent;        // 英雄列表容器
    public GameObject heroItemPrefab;        // 英雄项预制体
    public Text totalHeroCountText;          // 总英雄数量文本
    public Text unlockedHeroCountText;       // 已解锁英雄数量文本
    public Button addHeroButton;             // 添加英雄按钮
    public Button removeHeroButton;          // 删除英雄按钮
    public Button upgradeHeroButton;         // 升级英雄按钮
    
    [Header("测试设置")]
    public int testHeroId = 1;               // 测试用的英雄ID
    
    private HeroListModel _heroListModel;
    private List<GameObject> _heroItemInstances = new List<GameObject>();
    
    void Start()
    {
        Debug.Log("=== 英雄UI系统启动 ===");
        
        // 获取英雄列表模型
        _heroListModel = ModelManager.GetModel<HeroListModel>();
        
        // 添加监听器
        _heroListModel.AddHeroListChangedListener(OnHeroListChanged);
        
        // 设置按钮事件
        SetupButtons();
        
        // 初始化UI
        RefreshUI();
        
        // 创建一些测试英雄
        CreateTestHeroes();
    }
    
    void SetupButtons()
    {
        if (addHeroButton != null)
            addHeroButton.onClick.AddListener(OnAddHeroClicked);
            
        if (removeHeroButton != null)
            removeHeroButton.onClick.AddListener(OnRemoveHeroClicked);
            
        if (upgradeHeroButton != null)
            upgradeHeroButton.onClick.AddListener(OnUpgradeHeroClicked);
    }
    
    void CreateTestHeroes()
    {
        // 创建一些测试英雄
        var heroes = new List<HeroModel>
        {
            new HeroModel(1, "亚瑟"),
            new HeroModel(2, "妲己"),
            new HeroModel(3, "孙悟空"),
            new HeroModel(4, "貂蝉"),
            new HeroModel(5, "吕布")
        };
        
        // 设置一些初始属性
        heroes[0].Level = 5;
        heroes[0].Star = 3;
        heroes[0].Unlock();
        
        heroes[1].Level = 3;
        heroes[1].Star = 2;
        heroes[1].Unlock();
        
        heroes[2].Level = 1;
        heroes[2].Star = 1;
        
        heroes[3].Level = 2;
        heroes[3].Star = 1;
        heroes[3].Unlock();
        
        heroes[4].Level = 4;
        heroes[4].Star = 4;
        
        // 添加到模型
        _heroListModel.AddHeroes(heroes);
    }
    
    void OnAddHeroClicked()
    {
        // 添加一个新英雄
        int newHeroId = Random.Range(100, 999);
        string[] heroNames = { "赵云", "关羽", "张飞", "马超", "黄忠", "典韦", "许褚", "夏侯惇" };
        string randomName = heroNames[Random.Range(0, heroNames.Length)];
        
        var newHero = new HeroModel(newHeroId, randomName);
        newHero.Level = Random.Range(1, 10);
        newHero.Star = Random.Range(1, 6);
        
        _heroListModel.AddHero(newHero);
        
        Debug.Log($"UI添加英雄: {randomName} (ID: {newHeroId})");
    }
    
    void OnRemoveHeroClicked()
    {
        // 删除指定英雄
        if (_heroListModel.HasHero(testHeroId))
        {
            _heroListModel.RemoveHero(testHeroId);
            Debug.Log($"UI删除英雄 ID: {testHeroId}");
        }
        else
        {
            Debug.LogWarning($"英雄 ID {testHeroId} 不存在，无法删除");
        }
    }
    
    void OnUpgradeHeroClicked()
    {
        // 升级指定英雄
        var hero = _heroListModel.GetHero(testHeroId);
        if (hero != null)
        {
            if (Random.Range(0, 2) == 0)
            {
                hero.LevelUp();
                Debug.Log($"UI升级英雄: {hero.HeroName}");
            }
            else
            {
                hero.StarUp();
                Debug.Log($"UI升星英雄: {hero.HeroName}");
            }
        }
        else
        {
            Debug.LogWarning($"英雄 ID {testHeroId} 不存在，无法升级");
        }
    }
    
    void OnHeroListChanged(HeroListChangedEventArgs args)
    {
        switch (args.Type)
        {
            case HeroListChangedEventArgs.ChangeType.Added:
                Debug.Log($"[UI] 英雄列表添加: {args.Hero.HeroName}");
                RefreshHeroList();
                break;
                
            case HeroListChangedEventArgs.ChangeType.Removed:
                Debug.Log($"[UI] 英雄列表删除: {args.Hero.HeroName}");
                RefreshHeroList();
                break;
                
            case HeroListChangedEventArgs.ChangeType.Updated:
                Debug.Log($"[UI] 英雄属性更新: {args.Hero.HeroName}");
                UpdateHeroItem(args.Hero);
                break;
        }
        
        // 更新统计信息
        RefreshStatistics();
    }
    
    void RefreshUI()
    {
        RefreshHeroList();
        RefreshStatistics();
    }
    
    void RefreshHeroList()
    {
        // 清除现有UI项
        foreach (var item in _heroItemInstances)
        {
            if (item != null)
                Destroy(item);
        }
        _heroItemInstances.Clear();
        
        // 重新创建UI项
        foreach (var hero in _heroListModel.Heroes)
        {
            CreateHeroItem(hero);
        }
    }
    
    void CreateHeroItem(HeroModel hero)
    {
        if (heroItemPrefab == null || heroListContent == null)
            return;
            
        // 实例化英雄项
        GameObject heroItem = Instantiate(heroItemPrefab, heroListContent);
        _heroItemInstances.Add(heroItem);
        
        // 设置英雄项数据
        SetupHeroItem(heroItem, hero);
    }
    
    void SetupHeroItem(GameObject heroItem, HeroModel hero)
    {
        // 查找UI组件
        var nameText = heroItem.transform.Find("NameText")?.GetComponent<Text>();
        var levelText = heroItem.transform.Find("LevelText")?.GetComponent<Text>();
        var starText = heroItem.transform.Find("StarText")?.GetComponent<Text>();
        var attackText = heroItem.transform.Find("AttackText")?.GetComponent<Text>();
        var unlockButton = heroItem.transform.Find("UnlockButton")?.GetComponent<Button>();
        var upgradeButton = heroItem.transform.Find("UpgradeButton")?.GetComponent<Button>();
        
        // 设置文本
        if (nameText != null)
            nameText.text = hero.HeroName;
            
        if (levelText != null)
            levelText.text = $"Lv.{hero.Level}";
            
        if (starText != null)
            starText.text = $"★{hero.Star}";
            
        if (attackText != null)
            attackText.text = $"攻击: {hero.Attack:F0}";
        
        // 设置按钮状态和事件
        if (unlockButton != null)
        {
            unlockButton.gameObject.SetActive(!hero.IsUnlocked);
            unlockButton.onClick.RemoveAllListeners();
            unlockButton.onClick.AddListener(() => OnUnlockHeroClicked(hero));
        }
        
        if (upgradeButton != null)
        {
            upgradeButton.gameObject.SetActive(hero.IsUnlocked);
            upgradeButton.onClick.RemoveAllListeners();
            upgradeButton.onClick.AddListener(() => OnUpgradeHeroClicked(hero));
        }
        
        // 设置背景颜色（根据解锁状态）
        var background = heroItem.GetComponent<Image>();
        if (background != null)
        {
            background.color = hero.IsUnlocked ? Color.white : Color.gray;
        }
    }
    
    void UpdateHeroItem(HeroModel hero)
    {
        // 查找对应的UI项并更新
        for (int i = 0; i < _heroListModel.Heroes.Count; i++)
        {
            if (_heroListModel.Heroes[i].HeroId == hero.HeroId)
            {
                if (i < _heroItemInstances.Count && _heroItemInstances[i] != null)
                {
                    SetupHeroItem(_heroItemInstances[i], hero);
                }
                break;
            }
        }
    }
    
    void OnUnlockHeroClicked(HeroModel hero)
    {
        hero.Unlock();
        Debug.Log($"UI解锁英雄: {hero.HeroName}");
    }
    
    void OnUpgradeHeroClicked(HeroModel hero)
    {
        if (Random.Range(0, 2) == 0)
        {
            hero.LevelUp();
        }
        else
        {
            hero.StarUp();
        }
        Debug.Log($"UI升级英雄: {hero.HeroName}");
    }
    
    void RefreshStatistics()
    {
        if (totalHeroCountText != null)
            totalHeroCountText.text = $"总英雄: {_heroListModel.HeroCount}";
            
        if (unlockedHeroCountText != null)
            unlockedHeroCountText.text = $"已解锁: {_heroListModel.UnlockedHeroCount}";
    }
    
    void OnDestroy()
    {
        // 清理监听器
        if (_heroListModel != null)
        {
            _heroListModel.RemoveHeroListChangedListener(OnHeroListChanged);
        }
        
        // 清理按钮事件
        if (addHeroButton != null)
            addHeroButton.onClick.RemoveAllListeners();
        if (removeHeroButton != null)
            removeHeroButton.onClick.RemoveAllListeners();
        if (upgradeHeroButton != null)
            upgradeHeroButton.onClick.RemoveAllListeners();
    }
}

// 英雄项UI组件（用于预制体）
public class HeroItemUI : MonoBehaviour
{
    public Text nameText;
    public Text levelText;
    public Text starText;
    public Text attackText;
    public Button unlockButton;
    public Button upgradeButton;
    public Image background;
    
    private HeroModel _hero;
    
    public void SetHero(HeroModel hero)
    {
        _hero = hero;
        UpdateUI();
    }
    
    void UpdateUI()
    {
        if (_hero == null) return;
        
        if (nameText != null)
            nameText.text = _hero.HeroName;
            
        if (levelText != null)
            levelText.text = $"Lv.{_hero.Level}";
            
        if (starText != null)
            starText.text = $"★{_hero.Star}";
            
        if (attackText != null)
            attackText.text = $"攻击: {_hero.Attack:F0}";
            
        if (unlockButton != null)
            unlockButton.gameObject.SetActive(!_hero.IsUnlocked);
            
        if (upgradeButton != null)
            upgradeButton.gameObject.SetActive(_hero.IsUnlocked);
            
        if (background != null)
            background.color = _hero.IsUnlocked ? Color.white : Color.gray;
    }
} 